package com.woniuxy.lab.woniu_lab.commons;

import com.woniuxy.lab.woniu_lab.exception.WebException;
import org.springframework.beans.TypeMismatchException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingRequestValueException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;
import javax.xml.bind.ValidationException;

// 全局异常处理
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(WebException.class)
    public Result<Object> handleWebException(WebException e){
        e.printStackTrace();// 打印堆栈信息
        return Result.fail(e.getCode(), e.getMessage());
    }
    //请求参数错误
    @ExceptionHandler(TypeMismatchException.class)
    public Result<Object> TypeMismatchException(TypeMismatchException e){
        e.printStackTrace();// 打印堆栈信息
        return Result.fail(5008, "请求参数格式不合法");
    }
    @ExceptionHandler(MissingRequestValueException.class)
    public Result<Object> MissingRequestValueException(MissingRequestValueException e){
        e.printStackTrace();// 打印堆栈信息
        return Result.fail(5009, "请正确的传入参数");
    }
    @ExceptionHandler(ConstraintViolationException.class)
    public Result<Object> ConstraintViolationException(ConstraintViolationException e){
        e.printStackTrace();// 打印堆栈信息
        String[] split = e.getMessage().split(",");
        String message = "";
        for (int i = 0; i < split.length; i++) {
            message += split[i].substring(split[i].indexOf(":")+1);
            if (split.length-1 != i){
                message += ",";
            }
        }
        message = message.replace(" ", "");
        return Result.fail(5016, message);
    }
    /**
     * 参数校验异常抛出
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<Object> MethodArgumentNotValidException(MethodArgumentNotValidException e){
        StringBuilder messageBuilder = new StringBuilder();
        BindingResult bindingResult = e.getBindingResult();
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            messageBuilder
                    .append(fieldError.getField())
                    .append(":")
                    .append(fieldError.getDefaultMessage()).append(";");
        }

        return Result.fail(500,messageBuilder.toString());
    }

    @ExceptionHandler(Exception.class)
    public Result<Object> handleException(Exception e){
        e.printStackTrace();
        return Result.fail(500, "服务器繁忙");
    }

}
